<template>
  <div class="app-container">
    <el-tree default-expand-all :data="depts" :props="defaultProps" :expand-on-click-node="false">
      <template v-slot="{ data }">
        <el-row style="width:100%;height:40px" type="flex" justify="space-between" align="middle">
          <el-col>{{ data.name }}</el-col>
          <el-col :span="4">
            <span class="tree-manager">{{ data.managerName }}</span>
            <!-- $event 实参 表示类型 -->
            <el-dropdown @command="operateDept($event, data.id)">
              <!-- 显示区域内容 -->
              <span class="el-dropdown-link">
                操作<i class="el-icon-arrow-down el-icon--right" />
              </span>
              <!-- 下拉菜单选项 -->
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                <el-dropdown-item command="del">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-col>
        </el-row>
      </template>
    </el-tree>
    <AddDept ref="addDept" :node-id="nodeId" :visible.sync="showDialog" @updateDepts="getDepartment" />
  </div>
</template>

<script>
import { getDepartmentApi, delDepartmentApi } from '@/api/department'
import { transObjToTree } from '@/utils'
import AddDept from './components/add-dept.vue'
export default {
  name: 'Department',
  components: {
    AddDept
  },
  data() {
    return {
      // 1. 数据数组
      depts: [],
      // 2. 默认属性
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      showDialog: false, // 控制弹层显示隐藏
      nodeId: null
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    handleNodeClick(data) {
      console.log(data)
    },
    async  getDepartment() {
      const res = await getDepartmentApi()
      console.log(res)
      // console.log(transObjToTree(res, 0))
      this.depts = transObjToTree(res, 0)
    },
    operateDept(type, id) {
      // 下拉菜单触发事件
      if (type === 'add') {
        this.showDialog = true
        this.nodeId = id
      }
      if (type === 'edit') {
        // this.nodeId = id
        this.showDialog = true
        this.$nextTick(() => {
          this.$refs.addDept.getDepartmentDetail(id)
        })
      }
      // 3. 删除
      if (type === 'del') {
        this.$confirm('您确认要删除该部门吗').then(async() => {
          await delDepartmentApi(id)
          this.$message.success('删除部门成功~')
          this.getDepartment()
        })
      }
    }
  }
}
</script>

<style scoped lang="scss">
.app-container {
  padding: 30px 140px;
  font-size: 14px;
}
.tree-manager {
  width: 80px;
  display: inline-block;
  margin: 10px;
}
</style>
